package com.gexin.core;

import com.alibaba.druid.wall.WallFilter;
import com.gexin.common.AppGlobal;
import com.gexin.common.tag.RoleCheckTag;
import com.gexin.common.tag.TagKit;
import com.gexin.common.utils.BeetlStringKit;
import com.gexin.common.utils.QQiNiuUtil;
import com.gexin.common.utils.StringUtil;
import com.gexin.controller.IndexController;
import com.gexin.model._MappingKit;
import com.gexin.model.system.AdminConfig;
import com.gexin.model.system.RoleKit;
import com.gexin.plugin.sqlinxml.SqlInXmlPlugin;
import com.gexin.weixin.controller.WeixinEventMsgController;
import com.gexin.weixin.kit.WxConfigKit;
import com.jfinal.config.*;
import com.jfinal.core.JFinal;
import com.jfinal.ext.handler.UrlSkipHandler;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.ext.route.AutoBindRoutes;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.tx.TxByMethodRegex;
import com.jfinal.plugin.cron4j.Cron4jPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.render.ViewType;
import com.jfinal.template.Engine;
import net.dreamlu.event.EventPlugin;
import org.beetl.core.GroupTemplate;
import org.beetl.ext.jfinal3.JFinal3BeetlRenderFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * API引导式配置
 */
public class JfinalConfig extends JFinalConfig {
	private DruidPlugin druidPlugin;
	
	private static JFinal3BeetlRenderFactory rf = new JFinal3BeetlRenderFactory();
	/**
	 * 配置常量
	 */
	@Override
	public void configConstant(Constants me) {
		me.setViewType(ViewType.JSP);
		me.setError404View("/jsp/404.html");
		me.setError500View("/jsp/500.html");
		me.setError401View("/jsp/401.html");
		boolean dev = StringUtil.getBundelPath ("main","devMode").trim().equals("true")?true:false;
		// 加载少量必要配置，随后可用PropKit.get(...)获取值
		me.setDevMode(dev);
		if(dev){
			//载入测试模式的配置
			PropKit.use("gexin_config_debug.txt");	
		}else{
			//载入生成坏境的配置
			PropKit.use("gexin_config_run.txt");
		}
        rf.config();
        me.setRenderFactory(rf);
		//gt.registerTag("tag", Tag_Select.class);
		//设置全局的变量  在页面的任意地方可以拿到
	}
	
	public static void initBettlShareVars(){
		GroupTemplate gt = rf.groupTemplate;
		gt.registerFunctionPackage("beetlkit", BeetlStringKit.class);
		gt.registerFunctionPackage("strutil", StringUtil.class);
		gt.registerFunctionPackage("tagkit", TagKit.class);
		gt.registerTag("role",RoleCheckTag.class);
		AdminConfig  c  = AdminConfig.dao.getSysConfig();
		Map<String, Object>  map =new HashMap<String, Object>();
		map.put("webhost", AppGlobal.Web_Addr);
		map.put("basepath", c.getStaticCdnHost());
		map.put("global", c);//读取全部配置信息  在页面上  ${global.host_copy_right!};  属性参考 类AdminConfig 
		map.put("s_ver", c.getStaticAdminVer());//静态资源的版本
		gt.setSharedVars(map);
	}
	/**
	 * 配置路由
	 */
	@Override
	public void configRoute(Routes me) {
		me.setMappingSuperClass(true);
		me.add("/weixin/event/message", WeixinEventMsgController.class, "WEB-INF/system/");
	   	me.add("/", IndexController.class, "/indexs");// 第三个参数为该Controller的视图存放路径*/
		//me.add("/1", TestController.class);
	    AutoBindRoutes routes = new AutoBindRoutes();
		me.add(routes);

		//me.add("/system", AdminIndexController.class, "/index");
	}
	
	/**
	 * 配置插件
	 */
	@Override
	public void configPlugin(Plugins me) {

		// 配置C3p0数据库连接池插件
		//添加redis 缓存服务器
		if(PropKit.getBoolean("redis.enable")==true){
			RedisPlugin bbsRedis = new RedisPlugin(
											PropKit.get("redis.name")
											,PropKit.get("redis.ip")
											,PropKit.getInt("redis.port")
											,2000
											,PropKit.get("redis.pass")
											,PropKit.getInt("redis.database"));
			me.add(bbsRedis);
		}
		boolean execute_task = StringUtil.getBundelPath ("main","Execute_Task").trim().equals("true")?true:false;
		if(execute_task){
			Cron4jPlugin cp = new Cron4jPlugin("quartz/jobs.properties", "cron4j");
			me.add(cp);
		}
		me.add(new EhCachePlugin());  //添加缓存支持
/*		//mysql 连接池
		C3p0Plugin c3p0Plugin = new C3p0Plugin(PropKit.get("jdbcUrl"), PropKit.get("user"), PropKit.get("password").trim());
		me.add(c3p0Plugin);
	    // 配置ActiveRecord插件

*/		
			
			druidPlugin = new DruidPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"), PropKit.get("password"));
			druidPlugin.setMaxActive(PropKit.getInt("maxActive"));
			druidPlugin.setMinIdle(PropKit.getInt("minIdle"));
			druidPlugin.setInitialSize(PropKit.getInt("initialSize"));
			druidPlugin.setValidationQuery("select  current_date");//空闲时候去查询的语句防止异常
			
		    /*WallFilter  wall  = new WallFilter();
		    wall.setDbType("mysql");
	        druidPlugin.addFilter(wall);*/
		    //druidPlugin.addFilter(new StatFilter());
		   // druidPlugin.start();

			 SqlInXmlPlugin plugin = new SqlInXmlPlugin();
		     plugin.start();
	        //添加自动绑定model与表插件
			/* AutoTableBindPlugin autoTableBindPlugin = new AutoTableBindPlugin(druidPlugin, SimpleNameStyles.LOWER);
	        autoTableBindPlugin.start();
	        autoTableBindPlugin.setShowSql(false);
	        me.add(autoTableBindPlugin);*/
	        ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
	    	me.add(druidPlugin);
//			druidPlugin.addFilter(new WallFilter());
	    	_MappingKit.mapping(arp); //自动装载
	    	me.add(arp);

	    	//事件发送
			EventPlugin event_plugin = new EventPlugin();
			// 设置为异步，默认同步，或者使用`threadPool(ExecutorService executorService)`自定义线程池。
			event_plugin.async();
			me.add(event_plugin);

	   
	}
	
	/**
	 * 配置全局拦截器
	 */
	@Override
	public void configInterceptor(Interceptors me) {
		me.add(new SessionInViewInterceptor());
		//me.add(new ShiroInterceptor());
		//添加事务 的支持
		//me.add(new ShiroInterceptor());
		//me.add(new com.gexin.core.shiro.ShiroInterceptor());
		me.add(new TxByMethodRegex(".*save.*|.*delete.*|.*update.*"));
		//me.add(new TxByActionKeyRegex(regex));
		//me.add(new TxByMethods("save", "update"));
	}
	
	/**
	 * 配置处理器
	 */
	@Override
	public void configHandler(Handlers me) {
	     //me.add(new DruidStatViewHandler("/druid"));
		 me.add(new UrlSkipHandler(".+\\.\\w{1,4}",false)); //过滤静态资源的拦截器
		 //JFinal.me().getServletContext().setAttribute("title", "标题值在此");
		 me.add(new GlobalHandler());//添加全局的过滤器
		
		// me.add(new DruidStatViewHandler("/druid"));
	/*	me.add(new ContextPathHandler());
		me.add(new ACAOlHandler("*"));
		 me.add(new SessionHandler());
		*/
	}
	@Override
	public void onStart() {
		//百度编辑器 获取token的
		QQiNiuUtil.genUptoken();
		//初始化权限 管理 
		RoleKit.init();
		//初始化微信接口配置信息
		WxConfigKit.init();
        initBettlShareVars();
	}

	@Override
	public void onStop() {
		 druidPlugin.stop();
	}
	
	/**
	 * 建议使用 JFinal 手册推荐的方式启动项目
	 * 运行此 main 方法可以启动项目，此main方法可以放置在任意的Class类定义中，不一定要放于此
	 */
	public static void main(String[] args) {
		//JFinal.start("src/main/webapp", 80, "/", 5);
		JFinal.start("src/main/webapp", 808, "/", 0);
	}

	@Override
	public void configEngine(Engine arg0) {

	}
}
